package com.ldk.framework.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.service.IAlipayService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IPlatformFundFlowRecordService;
import com.ldk.framework.service.IRechargeOrderService;
import com.ldk.framework.service.IRechargeRecordService;
import com.ldk.framework.service.ITenpayService;
import com.ldk.framework.service.IUserService;
import com.ldk.framework.dao.IRechargeOrderDAO;
import com.ldk.framework.entity.Alipay;
import com.ldk.framework.entity.PlatformFundFlowRecord;
import com.ldk.framework.entity.RechargeOrder;
import com.ldk.framework.entity.RechargeRecord;
import com.ldk.framework.entity.Tenpay;
import com.ldk.framework.entity.User;
import com.ldk.framework.enums.FlowInOut;
import com.ldk.framework.enums.FlowPurpose;
import com.ldk.framework.enums.PayType;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.RechargeFrom;
import com.ldk.framework.enums.RechargeType;
import com.ldk.framework.enums.TradePayStatus;

/**
* RechargeOrderService接口实现类
* @author xiangwl
*/
@Service
public class RechargeOrderService extends BaseService<RechargeOrder> implements IRechargeOrderService {

	@Autowired
	private IRechargeOrderDAO rechargeOrderDAO;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDriverService driverService;
	@Autowired
	private IAlipayService alipayService;
	@Autowired
	private ITenpayService tenpayService;
	@Autowired
	private IRechargeRecordService rechargeRecordService;
	@Autowired
	private IPlatformFundFlowRecordService platformFundFlowRecordService;

	@Override
	protected IBaseDAO<RechargeOrder> getBaseDao() {
     	return this.rechargeOrderDAO;
	}

	@Override
	public Boolean payOrder(String dbKey, String orderNo, String payTradeNo,
			Tenpay tenpay, Alipay alipay) throws Exception {
		RechargeOrder orderQuery = new RechargeOrder();
		orderQuery.setRechargeOrderNo(orderNo);
		RechargeOrder order = selectByKey(dbKey, orderQuery);
		if(order == null)
			return false;
		if(order.getPayStatus() != TradePayStatus.WAIT_BUYER_PAY.getValue())
			return false;
		int userType = order.getUserType();
		if(userType != PlatformUserType.CLIENT_USER.getValue() &&
		   userType != PlatformUserType.DRIVER_USER.getValue())
			return false;
		User user = null;
		Driver driver = null;
		String openId = order.getRechargeUser();
		if(userType == PlatformUserType.CLIENT_USER.getValue()){
			user = userService.getUserByOpenId(dbKey, openId);
			if(user == null) return false;
		}
		else{
			driver = driverService.getDriverByOpenId(dbKey, openId);
			if(driver == null) return false;
		}
		
		RechargeOrder entity = new RechargeOrder();
		entity.setRechargeOrderNo(orderNo);
		entity.setPayTradeNo(payTradeNo);
		entity.setPayStatus(TradePayStatus.TRADE_SUCCESS.getValue());
		entity.setPayTime(SystemUtil.getAllSeconds());
		
		int row = updateByKey(dbKey, entity);
		if(row > 0){
			//修改支付记录信息
			//支付宝充值
			if(order.getPayId() == PayType.Alipay.getId()){
				if(alipay != null){
					Alipay query = new Alipay();
					query.setOutTradeNo(orderNo);//商户订单编号
					
					Alipay  existObj = alipayService.selectOne(dbKey, query);
					if(existObj != null){
						alipay.setPayId(existObj.getPayId());
						alipayService.updateByKey(dbKey, alipay);
					}
					else{
						alipayService.insert(dbKey, alipay);
					}
				}
			}
			//微信支付充值
			if(order.getPayId() == PayType.Tenpay.getId()){
				if(tenpay != null){
					Tenpay query = new Tenpay();
					query.setOutTradeNo(orderNo);//商户订单编号
					
					Tenpay existObj = tenpayService.selectOne(dbKey, query);
					if(existObj != null){
						tenpay.setPayId(existObj.getPayId());
						tenpayService.updateByKey(dbKey, tenpay);
					}
					else{
						tenpayService.insert(dbKey, tenpay);
					}
				}
			}
			//充值给用户
			double beforeBalance = 0;
			double afterBalance = 0;
			double rechargeMoney = 0;
			if(userType == PlatformUserType.CLIENT_USER.getValue()){
				beforeBalance = user.getBalance() == null ? 0 : user.getBalance();
				rechargeMoney =  order.getRechargeMoney() + order.getGiveMoney();
				afterBalance = beforeBalance + rechargeMoney;
				//修改用户余额
				long userId = user.getUserId();
				User userEntity = new User();
				userEntity.setUserId(userId);
				userEntity.setBalance(afterBalance);
				userService.updateByKey(dbKey, userEntity);
			}
			else{
				beforeBalance = driver.getBalance() == null ? 0 : driver.getBalance();
				rechargeMoney =  order.getRechargeMoney() + order.getGiveMoney();
				afterBalance = beforeBalance + rechargeMoney;
				//修改服务人员余额
				Driver driverEntity = new Driver();
				driverEntity.setDriverId(driver.getDriverId());
				driverEntity.setBalance(afterBalance);
				driverService.updateByKey(dbKey, driverEntity);
				
			}
			//添加充值记录
			int rechargeType = order.getPayId() == PayType.Alipay.getId() ? 
								  RechargeType.Alipay.getValue() : 
							      RechargeType.Weixin.getValue();
			String rechargeName = order.getPayId() == PayType.Alipay.getId() ? 
								  RechargeType.Alipay.getName() : 
								  RechargeType.Weixin.getName();
			String userTypeName = userType == PlatformUserType.CLIENT_USER.getValue() ? 
											  PlatformUserType.CLIENT_USER.getName() : 
											  PlatformUserType.DRIVER_USER.getName();
			String remark = String.format("%s使用%s充值", userTypeName, rechargeName);
			RechargeRecord record = new RechargeRecord();
			record.setRecordNo(SystemUtil.generateRandomNo(""));
			record.setPhoneNo(openId);
			record.setUserType(userType);
			record.setRechargeMoney(rechargeMoney);
			record.setRechargeFrom(RechargeFrom.FROM_APP.getValue());
			record.setBeforeBalance(beforeBalance);
			record.setAfterBalance(afterBalance);
			record.setRechargeTime(SystemUtil.getAllSeconds());
			record.setRechargeType(rechargeType);
			record.setOperator("system");
			record.setRemark(remark);
			//管理充值订单编号
			record.setLinkTaskNo(order.getRechargeOrderNo());
			//添加充值记录
			rechargeRecordService.insert(dbKey, record);
			
			//平台资金流动记录2条，1条资金流进2资金流出
			String purpose = userType == PlatformUserType.CLIENT_USER.getValue() ? 
										 FlowPurpose.USER_RECHARGE.getName() : 
										 FlowPurpose.DRIVER_RECHARGE.getName();
			//创建资金流进记录，流进金额＝充值金额
			double flowAmount = order.getRechargeMoney();
			
			PlatformFundFlowRecord flowRecordIn = new PlatformFundFlowRecord();
			flowRecordIn.setRecordNo(SystemUtil.generateRandomNo(""));
			flowRecordIn.setUserUniqueId(openId);
			flowRecordIn.setUserType(userType);
			flowRecordIn.setFlowAmount(flowAmount);
			flowRecordIn.setInOut(FlowInOut.IN.getValue());
			flowRecordIn.setFlowFrom("用户"+order.getPayName());
			flowRecordIn.setFlowTo("平台"+order.getPayName());
			flowRecordIn.setFlowMode(order.getPayId());
			flowRecordIn.setLinkNo(order.getRechargeOrderNo());
			flowRecordIn.setPurpose(purpose);
			platformFundFlowRecordService.insert(dbKey, flowRecordIn);
			
			//创建资金流出记录，流出的金额＝充值金额＋赠送金额
			flowAmount = order.getRechargeMoney() + order.getGiveMoney();
			
			PlatformFundFlowRecord flowRecordOut = new PlatformFundFlowRecord();
			flowRecordOut.setRecordNo(SystemUtil.generateRandomNo(""));
			flowRecordOut.setUserUniqueId(openId);
			flowRecordOut.setUserType(userType);
			flowRecordOut.setFlowAmount(flowAmount);
			flowRecordOut.setInOut(FlowInOut.OUT.getValue());
			flowRecordOut.setFlowFrom("平台"+order.getPayName());
			flowRecordOut.setFlowTo("用户"+order.getPayName());
			flowRecordOut.setFlowMode(order.getPayId());
			flowRecordOut.setLinkNo(order.getRechargeOrderNo());
			flowRecordOut.setPurpose(purpose);
			platformFundFlowRecordService.insert(dbKey, flowRecordOut);
			
			return true;
			
		}
		return false;
	}

}
